<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title></title>
		<style type="text/css">
			.item{
				width: 100px;
				height: 50px;
				border: 1px solid brown;
			}
		</style>
	</head>
	<body>
		<h2>点击切换颜色</h2>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
	</body>
	<script type="text/javascript">
		let item = document.getElementsByClassName("item");
		
		for (let i = 0; i < item.length; i++) {
			item[i].onclick = function(){
				console.log(i);// 0  1  2
				item[i].style.backgroundColor = "pink";
			}
			console.log(i);// 0  1  2
		}
		
		/* for (var i = 0; i < item.length; i++) {
			item[i].onclick = function(){
				console.log(i);// 3
				this.style.backgroundColor = "pink";
			}
			console.log(i);//  0  1  2
		} */
	</script>
</html>